package com.example.sunmiv1.activity;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.os.Bundle;
import android.os.RemoteException;
import android.os.Vibrator;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.sunmiv1.R;
import com.example.sunmiv1.entity.QuickVipInfo;
import com.example.sunmiv1.utils.ByteArrayTohexHepler;
import com.example.sunmiv1.utils.QR_code;
import com.example.sunmiv1.utils.ThreadPoolManager;
import com.example.sunmiv1.utils.Tools;
import com.example.sunmiv1.utils.net.ACache;
import com.example.sunmiv1.utils.net.Common;
import com.example.sunmiv1.utils.net.GsonUtils;
import com.example.sunmiv1.utils.net.HttpUtils;
import com.example.sunmiv1.utils.net.LoadingDialog;
import com.example.sunmiv1.utils.net.TextCallBack;
import com.example.sunmiv1.utils.printUtil;
import com.example.sunmiv1.utils.zxing.Constant;
import com.example.sunmiv1.utils.zxing.activity.CaptureActivity;

import org.application.ClientApplication;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.example.sunmiv1.utils.ByteArrayTohexHepler.ByteArrayToHexString;
import static com.example.sunmiv1.utils.ByteArrayTohexHepler.flipHexStr;


public class PayActivity extends Activity {

    @BindView(R.id.title_back)
    ImageView titleBack;
    @BindView(R.id.title_title)
    TextView titleTitle;
    @BindView(R.id.edit_pay)
    EditText editPay;
    @BindView(R.id.iv_pay)
    ImageView ivPay;
    @BindView(R.id.tv_pay_money)
    TextView tvPayMoney;
    @BindView(R.id.edit_pay_pass)
    EditText editPayPass;
    @BindView(R.id.tv_pay_cancel)
    TextView tvPayCancel;
    @BindView(R.id.tv_pay_confirm)
    TextView tvPayConfirm;
    @BindView(R.id.rl_pay)
    RelativeLayout rlPay;
    @BindView(R.id.btn_scan)
    Button btnScan;
    @BindView(R.id.edit_vip_code)
    EditText editVipCode;
    @BindView(R.id.tv_vip_confirm)
    TextView tvVipConfirm;
    @BindView(R.id.pay_vip_linear)
    LinearLayout payVipLinear;
    @BindView(R.id.tv_vip_name)
    TextView tvVipName;
    @BindView(R.id.tv_vip_balance)
    TextView tvVipBalance;

    private Intent intent;
    private Context context;
    private String money;
    private String payType;//1.微信 2.支付寶 3.會員卡
    private ACache aCache;
    public static PayActivity payActivity;
    private static final String TAG = "PayActivity";
    private String cardNum = "";
    private String order_no = "";
    private String out_trade_no = "";
    private String out_trade_no_qr = "";


    private LoadingDialog loadingDialog;

    //nfc
    private NfcAdapter mNfcAdapter;
    private PendingIntent pi;
    private boolean isSupportNfc, isOpenNfc;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_pay);
        context = this;
        ClientApplication.saveActivity(this);
        aCache = ACache.get(context);
        loadingDialog = new LoadingDialog(context);
        ButterKnife.bind(this);
        titleBack.setVisibility(View.VISIBLE);
        titleTitle.setText(R.string.payTitle);
        money = getIntent().getStringExtra("money");
        payType = getIntent().getStringExtra("payType");
        tvPayMoney.setText(money);

        if ("1".equals(payType) || "2".equals(payType)) {
            if ("1".equals(payType)) {

            } else {

            }
            GetCode();
        } else {
            ivPay.setVisibility(View.GONE);
            payVipLinear.setVisibility(View.VISIBLE);
            editVipCode.setFocusable(true);
            editVipCode.setFocusableInTouchMode(true);
        }

        //nfc
        PackageManager packageManager = this.getPackageManager();
        isSupportNfc = packageManager.hasSystemFeature(PackageManager.FEATURE_NFC);
        Log.e(TAG, "onCreate: isSupportNfc=" + isSupportNfc);
        if (isSupportNfc) {
            mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
            pi = PendingIntent.getActivity(this, 0, new Intent(this, getClass())
                    .addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
            if (mNfcAdapter != null && !mNfcAdapter.isEnabled()) {
                isOpenNfc = false;
            } else {
                isOpenNfc = true;
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mNfcAdapter != null && isSupportNfc && isOpenNfc) {
            mNfcAdapter.enableForegroundDispatch(this, pi, null, null);
        }
    }

    private boolean payFlag = true;

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        // Toast.makeText(context, "onNewIntent", Toast.LENGTH_SHORT).show();
        Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        //獲取 Tag 讀取 ID 得到字節數組  轉字符串 轉碼  得到卡號（默認16進制 這請自便）
        String num1 = ByteArrayToHexString(tag.getId());
        String num2 = flipHexStr(num1);
        Log.e(TAG, "onNewIntent: 1=" + num2);
        String num = "";
        if (num2.length() > 10) {
            try {
                num = ByteArrayTohexHepler.hex2String(num2);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            Long cardNo = Long.parseLong(num2, 16);
            Log.e(TAG, "onNewIntent: 2=" + cardNo);
            num = cardNo.toString();
        }
        if (num.length() != 10) {
            while (num.length() < 10) {
                num = "0" + num;
            }
        }
        Log.e("==================", num);
        cardNum = num;
        Log.e(TAG, "onNewIntent: ");
        //rlPay.setVisibility(View.VISIBLE);
        if (payType.equals("3") && payFlag) {
            payFlag = false;
            GetVipInfo();
        } else {
            Toast.makeText(this, "不是會員卡支付，請切換支付方式", Toast.LENGTH_SHORT).show();
        }
    }


    @OnClick({R.id.title_back, R.id.rl_pay, R.id.tv_pay_cancel, R.id.tv_pay_confirm, R.id.btn_scan,
            R.id.tv_vip_confirm})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                finish();
                break;
            case R.id.rl_pay:

                break;
            case R.id.tv_pay_cancel:
                payFlag = true;
                editPayPass.setText("");
                rlPay.setVisibility(View.GONE);
                break;
            case R.id.tv_pay_confirm:
                if (infoBean.getLogin_type() == 2) {//手機號
                    if ("1".equals(quickVipInfo.getDensity_free_state())) {//門店開啓免密支付
                        if (infoBean.getDensity_free().equals("2")) {//會員未開啓免密支付
                            if (TextUtils.isEmpty(editPayPass.getText().toString().trim())) {
                                Toast.makeText(context, "請輸入會員卡密碼", Toast.LENGTH_SHORT).show();
                            } else {
                                VipPay(infoBean);
                            }
                        } else {//會員開啓免密支付
                            VipPay(infoBean);
                        }
                    } else {//門店未開啓免密支付
                        if (TextUtils.isEmpty(editPayPass.getText().toString().trim())) {
                            Toast.makeText(context, "請輸入會員卡密碼", Toast.LENGTH_SHORT).show();
                        } else {
                            VipPay(infoBean);
                        }
                    }
                } else {
                    VipPay(infoBean);
                }
                break;
            case R.id.btn_scan:
                intent = new Intent(context, CaptureActivity.class);
                //intent.putExtra("type", payType);
                startActivityForResult(intent, 1);
                break;
            case R.id.tv_vip_confirm:
                if (TextUtils.isEmpty(editVipCode.getText().toString().trim())) {
                    Toast.makeText(context, "請輸入會員卡號/實體卡號/動態碼", Toast.LENGTH_SHORT).show();
                    return;
                }
                String code = editVipCode.getText().toString().trim();
                if (code.length() != 10 && code.length() != 11 && code.length() != 18) {
                    Toast.makeText(context, "請輸入正確的會員卡號/實體卡號/動態碼", Toast.LENGTH_SHORT).show();
                    return;
                }
                cardNum = code;
                GetVipInfo();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case 1:
                if (resultCode == RESULT_OK && data != null) {
                    Bundle bundle = data.getExtras();
                    String result = bundle.getString(Constant.INTENT_EXTRA_KEY_QR_SCAN);
                    if (!TextUtils.isEmpty(result)) {
                        checkQrCode(result);
                    }
                }
                break;
        }
    }

    private void checkQrCode(String result) {
        Log.e(TAG, "result:" + result);
        if (payType.equals("1") || payType.equals("2")) {
            if (Tools.isNumeric(result)) {
                int text = Integer.parseInt(result.substring(0, 2));
                boolean aliPay = (text >= 25 && text <= 30) ? true : false;
                boolean wxPay = (text >= 10 && text <= 15) ? true : false;
                if (aliPay || wxPay) {
                    Toast.makeText(context, "掃描成功", Toast.LENGTH_SHORT).show();
                    Pay(result);
                } else {
                    Toast.makeText(context, "不是正確的付款碼", Toast.LENGTH_SHORT).show();
                }
            }
        } else if (payType.equals("3")) {
            cardNum = result;
            editVipCode.setText("");
            GetVipInfo();
        }
        vibrate();
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onDestroy() {
        isQR = false;
        super.onDestroy();
    }

    private void vibrate() {
        Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
        vibrator.vibrate(200);
    }

    /*獲取支付寶微信二維碼*/
    private void GetCode() {
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("storeid", aCache.getAsString("storeid"));
            jsonObject.put("merchantid", aCache.getAsString("merchantid"));
            jsonObject.put("user_type", aCache.getAsString("userType"));
            jsonObject.put("operator_id", aCache.getAsString("uid"));
            jsonObject.put("pay_type", payType);
            jsonObject.put("pay_money", money);
            HttpUtils.post(context, Common.GET_CODE, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    loadingDialog.dismiss();
                    try {
                        JSONObject json = new JSONObject(text);
                        if (json.getInt("status") == 1) {
                            timer = new Timer();
                            timer.schedule(task, 0, 1000);
                            String url = json.getString("qr_code");
                            order_no = json.getString("out_trade_no");
//                            out_trade_no_qr = json.getJSONArray("data").getJSONObject(0).getString("out_trade_id");
                            ivPay.setImageBitmap(Tools.getCode(url, 200, 200));
                            queryStatus();
                        } else {
                            Toast.makeText(context, json.getString("msg"), Toast.LENGTH_SHORT).show();
                            order_no = "";
                            out_trade_no_qr = "";
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                protected void onFailure(ResponseException e) {
                    loadingDialog.dismiss();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /*支付寶微信掃碼支付*/
    boolean flag = false;
    boolean scanFlag = false;

    private void Pay(String code) {
        if (flag) {
            return;
        }
        flag = true;
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("storeid", aCache.getAsString("storeid"));
            jsonObject.put("merchantid", aCache.getAsString("merchantid"));
            jsonObject.put("user_type", aCache.getAsString("userType"));
            jsonObject.put("operator_identity_id", aCache.getAsString("uid"));
            jsonObject.put("pay_type", payType);
            jsonObject.put("pay_money", money);
            jsonObject.put("code", code);
            jsonObject.put("vip_login_type", 1);
            jsonObject.put("vid", "");
            jsonObject.put("password", "");
            jsonObject.put("card_code", "");
            if ("3".equals(aCache.getAsString("userType"))) {
                jsonObject.put("operator_id", aCache.getAsString("uid"));
            }else{
                jsonObject.put("operator_id",aCache.getAsString("operator_id"));
            }
            HttpUtils.post(context, Common.QUICK_CASHIER, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    loadingDialog.dismiss();
                    try {
                        JSONObject json = new JSONObject(text);
                        if (json.getInt("status") == 1) {
                            Log.e(TAG, "onSuccess: here00");
                            scanFlag = true;
                            out_trade_no = json.getString("out_trade_no");
                            printInfo();
                            intent = new Intent(context, CompleteActivity.class);
                            startActivity(intent);
                        } else {
                            flag = false;
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                protected void onFailure(ResponseException e) {
                    loadingDialog.dismiss();
                    flag = false;
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    boolean isVip = false;

    /**
     * 獲取會員信息
     */
    private QuickVipInfo quickVipInfo;
    QuickVipInfo.InfoBean infoBean;

    private void GetVipInfo() {
        Log.e(TAG, "GetVipInfo: ");
        if (isVip) {
            return;
        }
        loadingDialog.show();
        isVip = true;
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("vipCode", cardNum);
            jsonObject.put("storeid", aCache.getAsString("storeid"));
            jsonObject.put("merchantid", aCache.getAsString("merchantid"));
            jsonObject.put("user_type", aCache.getAsString("userType"));
            jsonObject.put("cashier_id", aCache.getAsString("uid"));
            HttpUtils.post(context, Common.MEMBER_INFO, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    loadingDialog.dismiss();
                    try {
                        JSONObject json = new JSONObject(text);
                        if (json.getInt("status") == 1) {
                            isVip = false;
                            quickVipInfo = GsonUtils.JsonToBean(text, QuickVipInfo.class);
                            infoBean = quickVipInfo.getInfo().get(0);
                            tvVipName.setText(infoBean.getNickname());
                            tvVipBalance.setText(getString(R.string.payTip) + infoBean.getBalance());
                            rlPay.setVisibility(View.VISIBLE);
                            if (infoBean.getLogin_type() == 2) {//手機號
                                if ("1".equals(quickVipInfo.getDensity_free_state())) {//門店開啓免密支付
                                    if (infoBean.getDensity_free().equals("2")) {//會員未開啓免密支付
                                        editPayPass.setVisibility(View.VISIBLE);
                                    } else {//會員開啓免密支付
                                        editPayPass.setVisibility(View.GONE);
                                    }
                                } else {//門店未開啓免密支付
                                    editPayPass.setVisibility(View.VISIBLE);
                                }
                            } else {
                                editPayPass.setVisibility(View.GONE);
                            }
                        } else {
                            Toast.makeText(context, json.getString("msg"), Toast.LENGTH_SHORT).show();
                            isVip = false;
                            payFlag = true;
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                protected void onFailure(ResponseException e) {
                    loadingDialog.dismiss();
                    isVip = false;
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /*會員卡支付*/
    private void VipPay(QuickVipInfo.InfoBean infoBean) {
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("storeid", aCache.getAsString("storeid"));
            jsonObject.put("merchantid", aCache.getAsString("merchantid"));
            jsonObject.put("user_type", aCache.getAsString("userType"));
            jsonObject.put("operator_identity_id", aCache.getAsString("uid"));
            jsonObject.put("pay_type", 6);
            jsonObject.put("pay_money", money);
            jsonObject.put("code", "");
            jsonObject.put("vip_login_type", infoBean.getLogin_type());
            jsonObject.put("vid", infoBean.getId());
            jsonObject.put("password", editPayPass.getText().toString().trim());
            jsonObject.put("card_code", infoBean.getPayCode());
            if ("3".equals(aCache.getAsString("userType"))) {
                jsonObject.put("operator_id", aCache.getAsString("uid"));
            }else{
                jsonObject.put("operator_id",aCache.getAsString("operator_id"));
            }
            HttpUtils.post(context, Common.QUICK_CASHIER, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    loadingDialog.dismiss();
                    try {
                        JSONObject json = new JSONObject(text);
                        Toast.makeText(context, json.getString("msg"), Toast.LENGTH_SHORT).show();
                        if (json.getInt("status") == 1) {
                            out_trade_no = json.getString("out_trade_no");
                            Log.e(TAG, "onSuccess: here111");
                            printInfo();
                            intent = new Intent(context, CompleteActivity.class);
                            startActivity(intent);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                protected void onFailure(ResponseException e) {
                    loadingDialog.dismiss();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /*private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1: //驗證會員存在
                    break;
                case 2: //會員不存在
                    break;
            }
        }
    };*/

    /*查詢訂單狀態*/
    private void queryStatus() {
        JSONObject json = new JSONObject();
        try {
            json.put("storeid", aCache.getAsString("storeid"));
            json.put("merchantid", aCache.getAsString("merchantid"));
            json.put("out_trade_no", order_no);
            json.put("type", 1);
            HttpUtils.post(context, Common.QUERY_ORDER, json, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    try {
                        JSONObject object = new JSONObject(text);
                        if (object.getInt("status") == 1) {
                            if (object.has("out_trade_no")) {
                                out_trade_no = object.getString("out_trade_no");
                            } else {
                                out_trade_no = order_no;
                            }
                            isQR = false;
                            Log.e(TAG, "onSuccess: here333");
                            if (!scanFlag) {
                                printInfo();
                            }
                            intent = new Intent(context, CompleteActivity.class);
                            startActivity(intent);
                        } else {

                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                protected void onFailure(ResponseException e) {

                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /*關閉訂單*/
    /*private void closeOther() {
        JSONObject json = new JSONObject();
        try {
            json.put("storeid", aCache.getAsString("storeid"));
            json.put("merchantid", aCache.getAsString("merchantid"));
            json.put("order_no", order_no);
            json.put("paytype", payType);
            json.put("ordertype", 1);
            HttpUtils.post(context, Common.CLOSE_ORDER, json, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    finish();
                }

                @Override
                protected void onFailure(ResponseException e) {

                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }*/


    private void printInfo() {
        if (printUtil.getInstance().woyouService != null) {

            SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日   HH:mm:ss");
            Date curDate = new Date(System.currentTimeMillis());
            ThreadPoolManager.getInstance().executeTask(() -> {
                try {
                    printUtil.getInstance().woyouService.setAlignment(1, null);
                    printUtil.getInstance().woyouService.printText("快速收單\n", null);
                    printUtil.getInstance().woyouService.setAlignment(0, null);
                    printUtil.getInstance().woyouService.printText("支付方式:", null);
                    switch (payType) {
                        case "0":
                            break;
                        case "1":
                            printUtil.getInstance().woyouService.printText("微信支付\n", null);
                            break;
                        case "2":
                            printUtil.getInstance().woyouService.printText("支付寶支付\n", null);
                            break;
                        case "3":
                            printUtil.getInstance().woyouService.printText("會員卡支付\n", null);
                            break;
                    }
                    printUtil.getInstance().woyouService.printText("支付金額:$" + money + "\n", null);
                    printUtil.getInstance().woyouService.printText("支付時間:\n" + formatter.format(curDate) + "\n", null);
                    printUtil.getInstance().woyouService.setAlignment(1, null);
                    printUtil.getInstance().woyouService.printBitmap(QR_code.createBarcode(out_trade_no, 400, 60), null);
                    printUtil.getInstance().woyouService.printBitmap(QR_code.createQRCode(out_trade_no, 300, 300), null);
                    printUtil.getInstance().woyouService.printText("\n請謹慎保管此小票，", null);
                    printUtil.getInstance().woyouService.lineWrap(5, null);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            });
        } else {
            Toast.makeText(context, "機器暫無打印功能", Toast.LENGTH_SHORT).show();
        }
    }

    private int recLen = 60;
    Timer timer;
    private boolean isQR = true;
    TimerTask task = new TimerTask() {
        @Override
        public void run() {
            runOnUiThread(() -> {
                recLen--;
                if (recLen <= 0) {
                    isQR = false;
                    timer.cancel();
                }
                if (isQR && !scanFlag) {
                    queryStatus();
                }
            });
        }
    };
}
